﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Concurrent;

namespace Bzure.Common.Caching.WeakCaching
{
    /// <summary>
    /// 存储管理器
    /// </summary>
    public class WeakStorageManager
    {
        private readonly ConcurrentDictionary<Key, object> _caches = new ConcurrentDictionary<Key, object>();

        public void Set<T>(string Key, T target, TimeSpan duration) where T : class
        {
            Set(Key, target, DateTime.Now.Add(duration));
        }
        public void Set<T>(string Key, T target, DateTime ExpirtTime) where T : class
        {
            Key CacheKey = new WeakCaching.Key(Key, typeof(T));
            CacheItem<T> item = new CacheItem<T>(target, ExpirtTime);
            _caches[CacheKey] = item;
        }
        public T Get<T>(string Key, Func<T> func, TimeSpan duration) where T : class
        {
            return Get(Key,func,DateTime.Now .Add (duration));
        }
        public T Get<T>(string Key, Func<T> func, DateTime ExpirtTime) where T : class
        {
            Key CacheKey = new WeakCaching.Key(Key, typeof(T));
            object obj = null;
            if (_caches.TryGetValue(CacheKey, out obj))
            {
                if (obj is CacheItem<T>)
                {
                    CacheItem<T> citem = obj as CacheItem<T>;
                    if (citem.IsCurrent)
                    {
                        return citem.Target;
                    }
                }
            }

            T target = func();
            CacheItem<T> item = new CacheItem<T>(target, ExpirtTime);
            _caches[CacheKey] = item;
            return target;
        }
    }
}
